extends Node2D

@export var damage = 10
@export var attack_cooldown = 1.5 # Time between attacks in seconds
@export var search_radius = 300.0

# Path to the projectile scene (if it shoots projectiles)
# @export var projectile_scene: PackedScene

@onready var attack_timer = $AttackTimer # Needs a Timer node named AttackTimer

var owner_player = null # Reference to the player owning this weapon

func _ready():
	attack_timer.wait_time = attack_cooldown
	attack_timer.one_shot = false # Make it repeat
	attack_timer.start()

func set_owner_player(player_node):
	owner_player = player_node

func _on_attack_timer_timeout():
	find_and_attack_enemy()

func find_and_attack_enemy():
	var closest_enemy = null
	var min_distance_sq = search_radius * search_radius # Use squared distance for efficiency

	# Get all enemies currently in the scene tree within the "enemies" group
	var enemies = get_tree().get_nodes_in_group("enemies")

	for enemy in enemies:
		# Ensure enemy is valid and hasn't been queued for deletion
		if is_instance_valid(enemy) and enemy.has_method("take_damage"):
			var distance_sq = global_position.distance_squared_to(enemy.global_position)
			if distance_sq < min_distance_sq:
				min_distance_sq = distance_sq
				closest_enemy = enemy

	if closest_enemy:
		attack(closest_enemy)

func attack(target_enemy):
	# --- Simple Melee Example (damage directly) ---
	print(name, " attacking ", target_enemy.name)
	target_enemy.take_damage(damage)
	# Add attack visual/sound effect here

	# --- Projectile Example (instantiate and shoot) ---
	# if projectile_scene:
	# 	var projectile = projectile_scene.instantiate()
	# 	# Add projectile to the main scene or a projectile container
	# 	get_tree().get_root().get_node("Main").add_child(projectile) # Adjust path as needed
	# 	projectile.global_position = global_position
	# 	projectile.target_direction = (target_enemy.global_position - global_position).normalized()
	# 	projectile.damage = damage


# Called by Player's apply_upgrade function
func upgrade_stat(stat_name, value):
	match stat_name:
		"damage":
			damage += value
			print(name, " damage upgraded to: ", damage)
		"speed": # Reduce cooldown
			attack_cooldown = max(0.1, attack_cooldown - value) # Ensure cooldown doesn't go below a minimum
			attack_timer.wait_time = attack_cooldown
			print(name, " attack cooldown reduced to: ", attack_cooldown)
		_:
			print("Unknown stat to upgrade for ", name, ": ", stat_name)

# Add a Timer node named "AttackTimer" as a child of this weapon scene in the editor.
# Connect its "timeout" signal to the _on_attack_timer_timeout function.
